﻿using UnityEngine;
using System.Collections;

public class UIButtonEffect : MonoBehaviour {

	public GameObject buttonImage;
	float startScaleValue = 0;
	public AnimationCurve idleScaleCurve = AnimationCurve.Linear(0,0,1,1);
	public float idleScaleValue = 1;
	public float idleScaleTime = 0.3f;
	public AnimationCurve pressCurve = AnimationCurve.Linear(0,0,1,1);
	public float pressValue = 0.8f;
	public float pressTime = 0.3f;
	public AnimationCurve chooseScaleCurve = AnimationCurve.Linear(0,0,1,1);
	public float chooseValue = 1.2f;
	public float chooseTime = 0.3f;
	public float duration = 0.2f;
	public Color pressed = new Color(183f / 255f, 163f / 255f, 123f / 255f, 1f);
	public Color disabledColor = Color.grey;
	int _pressindex = 0;
	void Awake(){
		InitFsm ();
	}
	void OnEnable(){
		RestPress ();
	}
	void Update(){
		buttonFsm.UpdateState (Time.deltaTime);
	}

	#region Fsm
	void InitFsm(){
		buttonFsm.AddState (idle, OnIdleEnter, OnIdleUpdate);
		buttonFsm.AddState (press, OnPressEnter, OnPressUpdate);
		buttonFsm.AddState (choose, OnChooseEnter, OnChooseUpdate);
	}

	FSM buttonFsm = new FSM ();
	StatePath idle = new StatePath("Idle");
	StatePath press = new StatePath("press");
	StatePath choose = new StatePath("choose");

	void OnIdleEnter(){
		TweenColor.Begin (buttonImage, duration, disabledColor);
		startScaleValue = getScale ();
	}
	void OnIdleUpdate(float dt){
		SetScale(Mathf.Lerp(startScaleValue,idleScaleValue,idleScaleCurve.Evaluate (buttonFsm.stateTime/idleScaleTime)));
	} 

	void OnPressEnter(){
		startScaleValue = getScale ();
		TweenColor.Begin (buttonImage, duration, pressed);
	}
	void OnPressUpdate(float dt){
		SetScale(Mathf.Lerp(startScaleValue,pressValue,pressCurve.Evaluate (buttonFsm.stateTime/pressTime)));
	
	}

	void OnChooseEnter(){
		startScaleValue =  Mathf.Min(getScale (),idleScaleValue);

	}
	void OnChooseUpdate(float dt){
		SetScale(Mathf.Lerp(startScaleValue,chooseValue,chooseScaleCurve.Evaluate (buttonFsm.stateTime/chooseTime)));
	}
	public void Choose(){ 
		buttonFsm.SetState (choose);
	}
	public void UnChoose(){
		buttonFsm.SetState (idle);
	}
	#endregion
	public void OnPress(bool active){
		
		if (active) {
			_pressindex++;
			if(_pressindex == 1)
			buttonFsm.SetState (press);
		}
		else {
			if(_pressindex>0)
				_pressindex--;
			if (_pressindex == 0) {
				if(!buttonFsm.IsState(idle))
					buttonFsm.SetState (idle);
			}
		}
	}

	float getScale(){
		return buttonImage.transform.localScale.x;
	}
	void SetScale(float value){
		buttonImage.transform.localScale = Vector3.one * value;
	}

	public void RestPress(){
		if (!buttonFsm.IsState (idle)) {
			SetScale (idleScaleValue);
			buttonFsm.SetState (idle);
			_pressindex = 0;
		}
	}
}
